var App = getApp()
var Api = require("../../common/api/api.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //是否已实名
    isRealName:false,

    //选择的空间图片
    chooseImg:"../../../image/icon/kj.jpg",

    //空间简介
    briefIntroduction: "",

    //实名认证证件号码（身份证）
    idNum:"",

    //空间展示图片名称（图片上传后获取名称）
    imgName:"",

    //空间名称
    name: "",
    
    //真实姓名
    realName:"" ,

    //随机字符串，
    randStr: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;

    //随机字符串生成
    _this.setData({
        randStr: _this.randomString(true, 8, 8),
    });


    //请求参数封装 
    var data = {
      openid: wx.getStorageSync('openid'),
    }
    var params = JSON.stringify(data)

    Api.isRealName(params).then(function (result) {
      _this.setData({
        isRealName: result.data.data
      });
    }).catch(function (error) {
      console.log(error)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },


  /**
   * 图片上传
   */
  chooseImage: function (e) {
    var that = this

    //wx.chooseImage 不多介绍看文档
    wx.chooseImage({
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],//压缩图
      count: 1,
      success: function (res) {
        console.log("选择的图片：", res.tempFilePaths[0]);
        that.setData({
          chooseImg: res.tempFilePaths[0]
        })
      }
    })
  },



  //下一步
  formSubmit: function (e) {
    let _this = this;

    console.log("提交数据：",e.detail.value);

    var briefIntroduction = e.detail.value.briefIntroduction;
    briefIntroduction = briefIntroduction.replace(/(^\s*)|(\s*$)/g, '');

    var name = e.detail.value.name;
    name = name.replace(/(^\s*)|(\s*$)/g, '');

    var chooseImg = _this.data.chooseImg;

    if (name == "") {
      App.showError("请填写空间名称");
      return;
    }

    if (chooseImg == "../../../image/icon/kj.jpg"){
      App.showError("请选择空间图片");
      return;
    }

    if (briefIntroduction == ""){
      App.showError("请填写空间简介");
      return;
    }
    
    _this.setData({
      briefIntroduction: briefIntroduction,
      name: name,
    });

    if (!_this.data.isRealName){
      wx.navigateTo({
        url: '../realname/realname?name=' + name + '&chooseImg=' + chooseImg + '&briefIntroduction=' + briefIntroduction,
      })
    }else{
      //上传图片
      wx.uploadFile({
        url: Api.host + "/api/fileUpload/upload",
        filePath: chooseImg,
        name: 'file',
        formData: {},
        method: 'POST',
        header: { "Content-Type": "multipart/form-data" },
        success: function (res) {
          var obj = JSON.parse(res.data);
          if (obj.code == 0) {
            //图片上传成功后业务处理
            _this.setData({
              imgName: obj.data
            });
          } else {
            App.showError(res.errMsg);
          }
        },
        fail: (res) => {
          console.log(res)
        },
        complete: () => {

          console.log("随机字符串：" + _this.data.randStr);

          //请求参数封装 
          var data = {
            briefIntroduction: _this.data.briefIntroduction,
            imgName: _this.data.imgName,
            name: _this.data.name,
            openid: wx.getStorageSync('openid'),
            randStr: _this.data.randStr,
          }
          var params = JSON.stringify(data)

          Api.createSpace(params).then(function (result) {
            if(result.data.code==0){
              App.showSuccess("创建成功");
              wx.switchTab({
                url: '../index',
              });
            }else{
              //随机字符串生成
              _this.setData({
                randStr: _this.randomString(true, 8, 8),
              });
            }
          }).catch(function (error) {
            console.log(error)
          })
        }
      })
    }
    
  },    


  randomString: function(randomLen, min, max){
    var str = "",
    range = min,
    arr =['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
      'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
      'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
      'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
      'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    // 随机产生
    if(randomLen) {
      range = Math.round(Math.random() * (max - min)) + min;
    }
    for(var i = 0; i<range; i++){
      var pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  }


})